import "whatwg-fetch";

let BASE_URL = "http://localhost:8888";
function request({ url, method = "get", params = {}, data = {} }) {
  if (!url) return;

  let options = {
    method,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      token: sessionStorage.getItem("token") || "",
    },
  };

  if (method === "post") {
    options.body = JSON.stringify(data);
  }
  console.log(options);

  return fetch(BASE_URL + url + "?" + jsonTo(params), options).then((res) =>
    res.json()
  );
}

function jsonTo(json) {
  let arr = [];
  for (var key in json) {
    arr.push(key + "=" + json[key]);
  }
  return arr.join("&");
}
export default request;
